// 自定义路由跳转
const goNavigate = (e, obj) => {
  let { url, disable } = obj || e.currentTarget.dataset
  if (disable) return wx.showModal({
    title: '提示',
    content: '敬请期待',
    showCancel: false, // 隐藏取消按钮
    // duration: 2000
  })
  // 校验当前用户是否已授权
  wx.getSetting({
    success({ authSetting }) {
      // 未授权 则开启自定义授权弹窗
      getApp().globalData.needUpdate = !authSetting['scope.userInfo']
      if (authSetting['scope.userInfo']) {
        wx.navigateTo({ url, success: res => Promise.resolve(res) })
      }
    }
  })
}
const getCookie = (scene = "") => {
  if (scene == "") return {}
  let res = {}
  let params = decodeURIComponent(scene).replace(/[ ]/g,"").split(",").flatMap(v => v.split(";"))
  params.forEach(item => {
    let pram = item.split("=")
    switch (pram[1]) {
      case 'true':
        res[pram[0]] = true
        break;
      case 'false':
        res[pram[0]] = false
        break;
    
      default:
        res[pram[0]] = pram[1]
        break;
    }
  })
  return res
}
// 获取二维码携带参数
const getScene = (scene = "") => {
  if (scene == "") return {}
  let res = {}
  let params = decodeURIComponent(scene).split("&")
  params.forEach(item => {
    let pram = item.split("=")
    res[pram[0]] = pram[1]
  })
  return res
}
//#region 获取胶囊（参数）
const getCapsuleParameter = () => {
  let { statusBarHeight, version, model, system } = wx.getSystemInfoSync()
  let { titleBarHeight } = _setCapsuleClearance(statusBarHeight, system)
  return {
    statusBarHeight, version, model, titleBarHeight,
    canUse: _compareVersion(version, '6.6.0') >= 0, // 是否支持自定义头部
    isIphonex: _isIphonex(model), // 是否为高屏手机（测试数据，待定）
  }
}
// 微信版本号比较
function _compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) { v1.push('0') }
  while (v2.length < len) { v2.push('0') }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])
    if (num1 > num2) return 1
    else if (num1 < num2) return -1
  }
  return 0
}
// 是否为高屏手机
function _isIphonex(model) {
  let shebei = ['iPhone X', 'iPhone11', 'MI 9']
  return shebei.some(v => model.startsWith(v))
}
/**
 * 设置胶囊上下间隙、及高度
 * @param {Number} statusBarHeight 状态栏高度 
 * @param {Object} system 设备系统信息
 */
function _setCapsuleClearance(statusBarHeight, system) {
  let jianxi
  if (wx.canIUse("getMenuButtonBoundingClientRect.top")) {
    // 同小程序API获取胶囊距顶间隙 - 状态栏高度
    jianxi = wx.getMenuButtonBoundingClientRect().top - statusBarHeight
  } else {
    // 根据手机系统设置不同的胶囊间隙
    if (system.startsWith('Android')) jianxi = 8
    else if (system.startsWith('iOS')) jianxi = 6
    else jianxi = 6
  }
  // 系统默认胶囊宽高为 87 32
  let titleBarHeight = 32 + jianxi * 2
  return {
    jianxi, titleBarHeight
  }
}
//#endregion

module.exports = {
  goNavigate, getScene, getCookie,
  getCapsuleParameter,
}